package Login;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class VerifyCode extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应头Content-type类型
        resp.setContentType("image/jpg");
        //获取二进制数据输出流对象
        ServletOutputStream out = resp.getOutputStream();
        //创建缓冲对象
        int width = 60;
        int height = 20;
        BufferedImage imgbuf = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = imgbuf.createGraphics();
        //设定背景色
        g.setColor(getRanColor(200, 200));
        //设定图像形状及宽高
        g.fillRect(0, 0, width, height);
        //随机产生100条干扰线，使图像中的验证码不容易被其他程序探测掉
        Random random = new Random();
        g.setColor(getRanColor(160, 200));
        for (int i = 0; i < 100; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x + x1, y + y1);
        }
        //随即产生干扰点，使图像中的验证码不易被其他分析程序探测到
        g.setColor(getRanColor(200, 200));
        for (int i = 0; i < 100; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        //随机产生0-9的数字
        g.setFont(new Font("times new Roman", Font.PLAIN, 18));//分别代表字体样式 字体格式 和 字体大小。
        String code = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            code += rand;
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
        }
        System.out.println("生成的随机数是" + code);
        //输出图像
        ImageIO.write(imgbuf, "JPEG", out);
        out.close();
    }

    private Color getRanColor(int i, int i1) {
        Random random = new Random();
        if (i > 255) {
            i = 255;
        }
        if (i < 0) {
            i = 0;
        }
        if (i1 > 255) {
            i1 = 255;
        }
        if (i1 < 0) {
            i1 = 0;
        }
        int r = i + random.nextInt(i1 - i);
        int g = i + random.nextInt(i1 - i);
        int b = i + random.nextInt(i1 - i);
        return new Color(r, g, b);
    }


}

